package com.sharemarking.wa.platform.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sharemarking.wa.common.Page;
import com.sharemarking.wa.common.ResponseParams;
import com.sharemarking.wa.common.entity.DriverVerify;
import com.sharemarking.wa.common.entity.OrgMember;
import com.sharemarking.wa.common.exception.*;
import com.sharemarking.wa.platform.service.OrderCommonFactory.*;
import com.sharemarking.wa.platform.dto.orderCommon.*;
import com.sharemarking.wa.platform.mapper.*;
import com.sharemarking.wa.platform.service.OrderCommonFactory.OrderCommonFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

import static com.sharemarking.wa.common.SysHttpStatus.*;

/**
 * @author dxy
 */
@Service
public class OrderCommonService {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private SecurityService ss;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private OrderCommonFactory orderCommonFactory;
    @Autowired
    private OrderCommonMapper orderCommonMapper;
    @Autowired
    private DriverVerifyMapper driverVerifyMapper;
    @Autowired
    private OrgMemberMapper orgMemberMapper;

    Map<Integer, List<Integer>> stateMap;

    OrderCommonService() {
        stateMap = new HashMap<>();
        //产废端状态码
        List<Integer> pwStateList = Arrays.asList(-1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11);
        //经营端状态码
        List<Integer> mStateList = Arrays.asList(-1, 3, 11, 4, 5, 7, 8, 9);
        //司机端状态码
        List<Integer> drStateList = Arrays.asList(-1, 7, 8, 9);
        //调度员和运输单位端状态码
        List<Integer> dpStateList = Arrays.asList(-1, 6, 7, 8, 9);

        stateMap.put(0, pwStateList);
        stateMap.put(1, mStateList);
        stateMap.put(2, drStateList);
        stateMap.put(3, dpStateList);
        stateMap.put(4, dpStateList);
    }


    public ResponseParams<?> getStateList() {
        Integer memberId = ss.getCurrentUserId();
        Integer role = memberMapper.getRoleByMemberId(memberId);

        List<StateListDto> stateList = new ArrayList<>();
        StateListDto s = new StateListDto();

        Map<String, Object> params = new HashMap<>();
        params.put("role", role);
        params.put("memberId", memberId);
        stateList.add(s.setName("全部").setState(-1).setValue(orderCommonMapper.getListTotal(params)));
        switch (role) {
            case 0:
                stateList.add(new StateListDto().setName("待处理").setState(0).setValue(orderCommonMapper.getStateValueBySendOrgMemberId(memberId, 0)));
                stateList.add(new StateListDto().setName("已完结").setState(1).setValue(orderCommonMapper.getStateValueBySendOrgMemberId(memberId, 1)));
                stateList.add(new StateListDto().setName("待经营商接单").setState(3).setValue(orderCommonMapper.getStateValueBySendOrgMemberId(memberId, 3)));
                stateList.add(new StateListDto().setName("待经营单位付款").setState(4).setValue(orderCommonMapper.getStateValueBySendOrgMemberId(memberId, 4)));
                stateList.add(new StateListDto().setName("待发布方付款").setState(11).setValue(orderCommonMapper.getStateValueBySendOrgMemberId(memberId, 11)));
                stateList.add(new StateListDto().setName("待运输单位接单").setState(5).setValue(orderCommonMapper.getStateValueBySendOrgMemberId(memberId, 5)));
                stateList.add(new StateListDto().setName("待运").setState(7).setValue(orderCommonMapper.getStateValueBySendOrgMemberId(memberId, 7) + orderCommonMapper.getStateValueBySendOrgMemberId(memberId, 6)));
                stateList.add(new StateListDto().setName("运输中").setState(8).setValue(orderCommonMapper.getStateValueBySendOrgMemberId(memberId, 8)));
                stateList.add(new StateListDto().setName("已完成").setState(9).setValue(orderCommonMapper.getStateValueBySendOrgMemberId(memberId, 9)));
                stateList.add(new StateListDto().setName("已取消").setState(10).setValue(orderCommonMapper.getStateValueBySendOrgMemberId(memberId, 10) + orderCommonMapper.getStateValueBySendOrgMemberId(memberId, 2)));
                break;
            case 1:
                stateList.add(new StateListDto().setName("待接单").setState(3).setValue(orderCommonMapper.getStateValueByReceiveOrgMemberId(memberId, 3)));
                stateList.add(new StateListDto().setName("待经营单位付款").setState(11).setValue(orderCommonMapper.getStateValueByReceiveOrgMemberId(memberId, 11)));
                stateList.add(new StateListDto().setName("待发布方付款").setState(4).setValue(orderCommonMapper.getStateValueByReceiveOrgMemberId(memberId, 4)));
                stateList.add(new StateListDto().setName("待运输单位接单").setState(5).setValue(orderCommonMapper.getStateValueByReceiveOrgMemberId(memberId, 5)));
                stateList.add(new StateListDto().setName("待运").setState(7).setValue(orderCommonMapper.getStateValueByReceiveOrgMemberId(memberId, 7)));
                stateList.add(new StateListDto().setName("运输中").setState(8).setValue(orderCommonMapper.getStateValueByReceiveOrgMemberId(memberId, 8)));
                stateList.add(new StateListDto().setName("已完成").setState(9).setValue(orderCommonMapper.getStateValueByReceiveOrgMemberId(memberId, 9)));
                break;
            case 2:
                stateList.add(new StateListDto().setName("待运").setState(7).setValue(orderCommonMapper.getStateValueByDriverId(memberId, 7)));
                stateList.add(new StateListDto().setName("运输中").setState(8).setValue(orderCommonMapper.getStateValueByDriverId(memberId, 8)));
                stateList.add(new StateListDto().setName("已完成").setState(9).setValue(orderCommonMapper.getStateValueByDriverId(memberId, 9)));
                break;
            case 3:
                stateList.add(new StateListDto().setName("待司机确认").setState(6).setValue(orderCommonMapper.getStateValueByTransportOrgMemberId(memberId, 6)));
                stateList.add(new StateListDto().setName("待运").setState(7).setValue(orderCommonMapper.getStateValueByTransportOrgMemberId(memberId, 7)));
                stateList.add(new StateListDto().setName("运输中").setState(8).setValue(orderCommonMapper.getStateValueByTransportOrgMemberId(memberId, 8)));
                stateList.add(new StateListDto().setName("已完成").setState(9).setValue(orderCommonMapper.getStateValueByTransportOrgMemberId(memberId, 9)));
                break;
            case 4:
                Integer orgId = orgMemberMapper.selectOne(new QueryWrapper<OrgMember>().eq("member_id", memberId)).getOrgId();
                stateList.add(new StateListDto().setName("待司机确认").setState(6).setValue(orderCommonMapper.getStateValueByTransportOrgId(orgId, 6)));
                stateList.add(new StateListDto().setName("待运").setState(7).setValue(orderCommonMapper.getStateValueByTransportOrgId(orgId, 7)));
                stateList.add(new StateListDto().setName("运输中").setState(8).setValue(orderCommonMapper.getStateValueByTransportOrgId(orgId, 8)));
                stateList.add(new StateListDto().setName("已完成").setState(9).setValue(orderCommonMapper.getStateValueByTransportOrgId(orgId, 9)));
                break;
        }

        return ResponseParams.ok(stateList);
    }


    public ResponseParams<?> getOrderList() throws Exception {
        Integer memberId = ss.getCurrentUserId();

        String state = request.getParameter("state");
        if (StringUtils.isEmpty(state)) {
            throw RequestException.create(ResponseParams.requiredParamsIsMissing("state"));
        }

        int pageIndex = Integer.parseInt(StringUtils.isEmpty(request.getParameter("pageIndex")) ? "1" : request.getParameter("pageIndex"));
        int pageSize = Integer.parseInt(StringUtils.isEmpty(request.getParameter("pageSize")) ? "10" : request.getParameter("pageSize"));

        Map<String, Object> params = new HashMap<>();
        params.put("pageIndex", (pageIndex - 1) * pageSize);
        params.put("pageSize", pageSize);
        params.put("memberId", memberId);
        Integer stateInt = Integer.valueOf(state);

        Integer role = memberMapper.getRoleByMemberId(memberId);
        //对state进行验证
        List<Integer> stateList = stateMap.get(role);
        if (!stateList.contains(stateInt)) {
            throw RequestException.create(ResponseParams.isDataError("状态码错误"));
        }

        if (stateInt != -1) {
            params.put("state", state);
        }

        if (role == 1 || role == 0) {
            //经营商 和 产废端
            Integer examState = orderCommonMapper.isOrgVerify(memberId);
            if (examState == null || examState != 1) {
                if (role == 0) {
                    throw OrgException.create(ResponseParams.error(UN_P_ORG_VERIFY));
                } else if (role == 1) {
                    throw OrgException.create(ResponseParams.error(UN_M_ORG_VERIFY));
                }
            }
        } else if (role == 2) {
            //司机端
            DriverVerify driverVerify = driverVerifyMapper.selectOne(new QueryWrapper<DriverVerify>().eq("member_id", memberId).eq("exam_state", 1));
            if (driverVerify == null) {
                throw DriverException.create(ResponseParams.error(UN_DRIVER_VERIFY));
            } else {
                params.put("driverId", driverVerify.getMemberId());
            }
        }
        params.put("role", role);

        List<OrderListDto> orderList = orderCommonFactory.getOrderList(params);
        if (role == 4) {
            for (OrderListDto tem : orderList)
                tem.setOperate(null);
        }
        return ResponseParams.ok(new Page<>(orderList, pageIndex, pageSize, orderCommonMapper.getListTotal(params), orderList.size() == pageSize));
    }


    public ResponseParams<?> getOrderInfo() throws Exception {
        Integer memberId = ss.getCurrentUserId();
        String code = request.getParameter("code");

        if (StringUtils.isEmpty(code)) {
            throw RequestException.create(ResponseParams.requiredParamsIsMissing("code"));
        }
        Map<String, Object> params = new HashMap<>();
        Integer role = memberMapper.getRoleByMemberId(memberId);
        params.put("code", code);
        params.put("role", role);
        params.put("memberId", memberId);
        OrderInfoDto orderInfoDto = orderCommonFactory.getOrderInfo(params);
        if (role == 4)
            orderInfoDto.setOperate(null);
        return ResponseParams.ok(orderInfoDto);
    }


    public ResponseParams<?> getTaskOrderList() throws Exception {
        String types = request.getParameter("types");
        String searchStr = request.getParameter("searchStr");

        if (StringUtils.isEmpty(types)){
            throw RequestException.create(ResponseParams.requiredParamsIsMissing("types"));
        }

        Integer memberId = ss.getCurrentUserId();

        int pageIndex = Integer.parseInt(StringUtils.isEmpty(request.getParameter("pageIndex")) ? "1" : request.getParameter("pageIndex"));
        int pageSize = Integer.parseInt(StringUtils.isEmpty(request.getParameter("pageSize")) ? "10" : request.getParameter("pageSize"));

        Map<String, Object> params = new HashMap<>();
        params.put("pageIndex", (pageIndex - 1) * pageSize);
        params.put("pageSize", pageSize);
        params.put("memberId", memberId);
        if (!StringUtils.isEmpty(searchStr)) {
            params.put("searchStr", searchStr);
        }
        //获取所属角色
        Integer role = memberMapper.getRoleByMemberId(memberId);
        if (Integer.parseInt(types) == 0) {
            if (role == 0) {
                //产废端没有此功能
                throw RequestException.create(ResponseParams.error(REQUIRED_PARAMS_ERROR));
            } else if (role == 1) {
                //经营商
                if (orderCommonMapper.isOrgVerify(memberId) == null || orderCommonMapper.isOrgVerify(memberId) != 1) {
                    throw OrgException.create(ResponseParams.error(UN_M_ORG_VERIFY));
                }

                params.put("orgId", orgMemberMapper.selectOne(new QueryWrapper<OrgMember>().eq("member_id", memberId)).getOrgId());
            } else if (role == 2) {
                //司机端
                DriverVerify driverVerify = driverVerifyMapper.selectOne(new QueryWrapper<DriverVerify>().eq("member_id", memberId).eq("exam_state", 1));
                if (driverVerify == null) {
                    throw DriverException.create(ResponseParams.error(UN_DRIVER_VERIFY));
                } else {
                    params.put("driverId", driverVerify.getMemberId());
                }
            }
            if (role == 3)
                params.put("state",5);


            params.put("role", role);


            List<TaskOrderListDto> taskOrderList = orderCommonFactory.getTaskOrderList(params);
            Integer taskOrderListTotal = orderCommonMapper.getTaskOrderListTotal(params);
            return ResponseParams.ok(new Page<>(taskOrderList, pageIndex, pageSize, taskOrderListTotal, taskOrderList.size() == pageSize));
        }
        else {
            Integer stateInt = 3;

            //对state进行验证
//            List<Integer> stateList = stateMap.get(role);
//            if (!stateList.contains(stateInt)){
//                throw RequestException.create(ResponseParams.isDataError("状态码错误"));
//            }
            if (role != 3)
                params.put("state", stateInt);

            if (role == 1 || role == 0) {
                //经营商 和 产废端
                Integer examState = orderCommonMapper.isOrgVerify(memberId);
                if (examState == null || examState != 1) {
                    if (role == 0) {
                        throw OrgException.create(ResponseParams.error(UN_P_ORG_VERIFY));
                    } else if (role == 1) {
                        throw OrgException.create(ResponseParams.error(UN_M_ORG_VERIFY));
                    }
                }
            } else if (role == 2) {
                //司机端
                DriverVerify driverVerify = driverVerifyMapper.selectOne(new QueryWrapper<DriverVerify>().eq("member_id", memberId).eq("exam_state", 1));
                if (driverVerify == null) {
                    throw DriverException.create(ResponseParams.error(UN_DRIVER_VERIFY));
                } else {
                    params.put("driverId", driverVerify.getMemberId());
                }
            }
            params.put("role", role);

            List<OrderListDto> orderList = orderCommonFactory.getOrderList(params);
            if(role == 4){
                for (OrderListDto tem:orderList)
                    tem.setOperate(null);
            }
            List<TaskOrderListDto> taskOrderList = new ArrayList<>();
            for (OrderListDto i:orderList){
                TaskOrderListDto ad = new TaskOrderListDto();
                ad.setId(i.getId());
                ad.setParentId(i.getParentId());
                ad.setCode(i.getCode());
                ad.setPublishOrgName(i.getOrgName());
                ad.setState(i.getState());
                ad.setDistance(i.getDistance());
                ad.setLoadingAddress(i.getLoadingAddress());
                ad.setUnLoadingAddress(i.getUnLoadingAddress());
                ad.setWasteList(i.getWasteList());
                ad.setOperate(i.getOperate());
                ad.setIsOrgVerify(1);
                ad.setIsUrgent(i.getIsUrgent());
                taskOrderList.add(ad);
            }
            return ResponseParams.ok(new Page<>(taskOrderList, pageIndex, pageSize, orderCommonMapper.getListTotal(params), orderList.size() == pageSize));
        }
    }


    public ResponseParams<?> getTaskOrderInfo() throws Exception {
        Integer memberId = ss.getCurrentUserId();
        String code = request.getParameter("code");

        if (StringUtils.isEmpty(code)) {
            throw RequestException.create(ResponseParams.requiredParamsIsMissing("code"));
        }
        Map<String, Object> params = new HashMap<>();
        Integer role = memberMapper.getRoleByMemberId(memberId);
        params.put("code", code);
        params.put("role", role);

        OrderInfoDto orderInfoDto = orderCommonFactory.getTaskOrderInfo(params);
        return ResponseParams.ok(orderInfoDto);
    }
}
